package com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.SimEarthquake;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.queryParams.EarEveManageQuaParams;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.vo.EarEveManageVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.heaManage.entity.HeaManage;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.web.PlatformSessionContext;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class EarEveManageRepositoryImpl implements EarEveManageRepository {
    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public Map<String, Object> getPage(EarEveManageQuaParams queParams, int curPage, int pageSize) {
        /*StringBuilder sql = new StringBuilder("select * from xczh_seismic_event_management");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0'");
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;
        String userID = PlatformSessionContext.getUserID();
        StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        if (!PlatformObjectUtils.isEmpty(queParams.getEventName())) {
            whereSql.append(" and event_name like '%" + queParams.getEventName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queParams.getMagnitude())) {
            whereSql.append(" and magnitude like '%" + queParams.getMagnitude() + "%'");
        }

        if(!PlatformObjectUtils.isEmpty(userID)){
            whereSql.append(" and create_user = '" + userID + "'");
        }

        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(EarEveManage.class)).size();
        List<EarEveManage> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(EarEveManage.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;*/
        String userId = PlatformSessionContext.getUserID();
        StringBuilder sql = new StringBuilder("select a.* ,COALESCE(b.is_current_event, '0') isCurrentEvent from xczh_seismic_event_management " +
                "a left join xczh_seismic_event_user b on a.xsem_id=b.xsem_id and b.user_id='"+userId+"'");
        StringBuilder whereSql = new StringBuilder(" where a.del_flag='0' and (a.xsem_id in (select xsem_id from " +
                "xczh_personnel_info_management b where b.del_flag='0' and b.uuid='"+userId+"') or a.create_user='"+userId+"')");
        StringBuilder orderSql = new StringBuilder(" order by a.create_time desc");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;

        StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        if (!PlatformObjectUtils.isEmpty(queParams.getEventName())) {
            whereSql.append(" and a.event_name like '%" + queParams.getEventName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queParams.getMagnitude())) {
            whereSql.append(" and a.magnitude like '%" + queParams.getMagnitude() + "%'");
        }
        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(EarEveManage.class)).size();
        List<EarEveManageVo> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(EarEveManageVo.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public EarEveManage findById(String id) {
        String sql="select * from xczh_seismic_event_management where xsem_id = ? ";
        EarEveManage earEveManage = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(EarEveManage.class), id);
        return earEveManage;
    }

    @Override
    public void delete(String id) {
        String sql = "update xczh_seismic_event_management set del_flag= ? where xsem_id = ?";
        jdbcTemplate.update(sql, YNEnum.Y.toString(),id);
    }

    @Override
    public void completion(String id) {
        String sql = "update xczh_seismic_event_management set event_status= ? where xsem_id = ?";
        jdbcTemplate.update(sql, YNEnum.Y.toString(),id);
    }

    @Override
    public void update(EarEveManage earEveManage) {
        String sql="update xczh_seismic_event_management set event_name = :eventName " +
                ",update_user = :updateUser ,update_time = :updateTime where xsem_id = :xsemId";
        SqlParameterSource source = new BeanPropertySqlParameterSource(earEveManage);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void save(EarEveManage earEveManage) {
        //经纬度组成空间字段数据
        String longitude = earEveManage.getLongitude().toString();
        String latitude = earEveManage.getLatitude().toString();
        String geom = "POINT("+longitude+" "+latitude+")";
        earEveManage.setGeom(geom);
        String sql="insert into xczh_seismic_event_management(xsem_id,seismic_code,event_code,event_name,event_status,event_time," +
                "epicentral_site,magnitude,create_user,create_time,update_user,update_time,del_flag,create_unit,is_relation,create_user_name,longitude,latitude,source_depth,end_time,geom,province,city,county,jsc_id) " +
                "values(:xsemId, :seismicCode, :eventCode, :eventName, :eventStatus, :eventTime, :epicentralSite, :magnitude, :createUser, " +
                ":createTime, :updateUser, :updateTime, :delFlag, :createUnit, :isRelation, :createUserName,:longitude,:latitude,:sourceDepth,:endTime,st_geomfromtext(:geom,4490),:province,:city,:county,:jscId)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(earEveManage);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateRelationStatus(String xsemId) {
        String sql = "update xczh_seismic_event_management set is_relation= ? where xsem_id = ?";
        jdbcTemplate.update(sql, YNEnum.Y.toString(),xsemId);
    }

    @Override
    public EarEveManage selWheHavCurEvent(String id,String userId) {
        String sql="select * from xczh_seismic_event_management where is_current_event = ? and xsem_id != ? and create_user= ?";
        EarEveManage earEveManage=new EarEveManage();
        try {
            earEveManage = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(EarEveManage.class), YNEnum.Y.toString(), id,userId);
            return earEveManage;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void updateCurEvent(String id) {
        String sql="update xczh_seismic_event_management set is_current_event = ? where xsem_id != ?";
        jdbcTemplate.update(sql,YNEnum.N.toString(),id);
    }

    @Override
    public void setCurEvent(String id) {
        String sql="update xczh_seismic_event_management set is_current_event = ? where xsem_id = ?";
        jdbcTemplate.update(sql,YNEnum.Y.toString(),id);
    }

    @Override
    public EarEveManage findBySeismicCode(String seismicCode) {
        String sql="select * from xczh_seismic_event_management where del_flag= ? and seismic_code = ? ";
        EarEveManage earEveManage=null;
        try {
            List<EarEveManage> earEveManages = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EarEveManage.class), YNEnum.N.toString(),seismicCode);
            if(ObjectUtils.isNotEmpty(earEveManages) && earEveManages.size()>0){
                earEveManage = earEveManages.get(0);
            }
            return earEveManage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    public EarEveManage findByJscId(String jscId) {
        String sql="select * from xczh_seismic_event_management where del_flag= ? and jsc_id = ? ";
        EarEveManage earEveManage=null;
        try {
            List<EarEveManage> earEveManages = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EarEveManage.class), YNEnum.N.toString(),jscId);
            if(ObjectUtils.isNotEmpty(earEveManages) && earEveManages.size()>0){
                earEveManage = earEveManages.get(0);
            }
            return earEveManage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public EarEveManage getCurrentEvent(String userId) {
        String sql="select a.*,COALESCE(b.is_current_event, '0') isCurrentEvent from xczh_seismic_event_management a " +
                "left join xczh_seismic_event_user b on a.xsem_id=b.xsem_id where a.del_flag= ? and b.user_id = ? ";
        EarEveManage earEveManage=new EarEveManage();
        try {
            earEveManage = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(EarEveManage.class),YNEnum.N.toString(),userId);
            return earEveManage;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<EarEveManage> getList() {
        String sql = "select * from xczh_seismic_event_management where del_flag = '0' order by create_time desc";
   /*     Integer total = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EarEveManage.class)).size();*/
        List<EarEveManage> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EarEveManage.class));
        return list;
    }

    @Override
    public List<EarEveManage> getAllEarEveManage() {
        StringBuilder sql = new StringBuilder("select * from xczh_seismic_event_management  where del_flag = '0' order by create_time desc");
        List<EarEveManage> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(EarEveManage.class));
        return list;
    }

    @Override
    public void updateEventStatus(String id, String status) {
        String sql="update xczh_seismic_event_management set event_status = ? where xsem_id = ?";
        jdbcTemplate.update(sql,status,id);
    }

    @Override
    public List<EarEveManageVo> getAppPage() {
        String userId = PlatformSessionContext.getUserID();
        StringBuilder sql = new StringBuilder("select a.* ,COALESCE(b.is_current_event, '0') isCurrentEvent from xczh_seismic_event_management " +
                "a left join xczh_seismic_event_user b on a.xsem_id=b.xsem_id and b.user_id='"+userId+"'");
        StringBuilder whereSql = new StringBuilder(" where a.del_flag='0' and a.xsem_id in (select xsem_id from " +
                "xczh_personnel_info_management b where b.del_flag='0' and b.uuid='"+userId+"') or a.create_user='"+userId+"'");
        StringBuilder orderSql = new StringBuilder(" order by a.create_time desc");

        sql.append(whereSql).append(orderSql);
        List<EarEveManageVo> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(EarEveManageVo.class));
        return list;
    }

    @Override
    public void endSeismicEvent(String id, String eventStatus, Date endTime) {
        String sql="update xczh_seismic_event_management set event_status = ? , end_time = ? where xsem_id = ?";
        jdbcTemplate.update(sql,eventStatus,endTime,id);
    }

    @Override
    public EarEveManage getByCondition(String longitude, String latitude, String magnitude,String eventTime) {
        StringBuilder sql = new StringBuilder("select * from xczh_seismic_event_management  " +
                "where del_flag = '0' and longitude = '"+longitude+"' and latitude = '"+latitude+"' and magnitude = '"+magnitude+"' " +
                "and event_time = '"+eventTime+"' " +
                "order by create_time desc limit 1");
        EarEveManage earEveManage=new EarEveManage();
        try {
            earEveManage = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<>(EarEveManage.class));
            return earEveManage;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void updateFileIdById(String xsemId, String attachId) {
        String sql = "update xczh_seismic_event_management set attach_id='"+attachId+"' where xsem_id='"+xsemId+"'";
        jdbcTemplate.update(sql);
    }
}
